package mspbots.cw.client.core.data.times;

import com.fasterxml.jackson.databind.JsonNode;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import mspbots.cw.client.core.AbstractToolsUtil;
import mspbots.cw.client.core.data.BaseApiService;
import mspbots.cw.client.core.app.SyncRequest;
import mspbots.cw.client.core.client.ClientProperties;
import mspbots.cw.common.*;
import mspbots.cw.common.callback.CallbackAction;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

/**
 * com.mspbots.sync.scheduled.service.TimeEnTriesService
 *
 * @author Alex bob(https://github.com/vnobo)
 * @date Created by 2019/6/10
 */
@Log4j2
@Service
@RequiredArgsConstructor
public class TimeEntriesServiceImpl extends AbstractToolsUtil implements BaseApiService {

    @Override
    public Flux<JsonNode> find(Long tenantId, QueryParams queryParams) {
        ResultSync resultSync = ResultSync.withDefault("TIME-ENTRIES-SEARCH");
        return this.loadProperties(tenantId)
                .flatMapMany(properties -> this.get(properties, queryParams))
                .contextWrite(ctx -> ctx.put("resultSync", resultSync));
    }

    private Flux<JsonNode> get(ClientProperties properties, QueryParams queryParams) {
        return super.cwWebClient.get("/time/entries", queryParams)
                .flatMapMany(Flux::fromIterable)
                .contextWrite(ctx -> ctx.put("properties", properties));
    }


    @Override
    public Mono<JsonNode> count(Long tenantId, QueryParams queryParams) {
        ResultSync resultSync = ResultSync.withDefault("TIME-ENTRIES-COUNT");
        return super.loadProperties(tenantId)
                .flatMap(clientProperties -> this.count(clientProperties, queryParams))
                .contextWrite(ctx -> ctx.put("resultSync", resultSync));
    }

    private Mono<JsonNode> count(ClientProperties properties, QueryParams queryParams) {
        return super.cwWebClient.get("/time/entries/count", queryParams)
                .contextWrite(ctx -> ctx.put("properties", properties));
    }

    @Override
    public Mono<Void> manualSync(ClientProperties properties, SyncRequest syncRequest) {
        ResultSync resultSync = ResultSync.withDefault("MANUAL-TIME-ENTRIES-SYNC");
        String conditionsStr = "lastUpdated>=[" + syncRequest.getBeginTime().format(DateTimeFormatter.ISO_DATE_TIME) +
                "] and lastUpdated <=[" + syncRequest.getEndTime().format(DateTimeFormatter.ISO_DATE_TIME) + "]";
        return this.fetch(properties, QueryParams.withDefault().setConditions(conditionsStr)
                .setOrderBy("lastUpdated asc"))
                .contextWrite(ctx -> ctx.put("resultSync", resultSync))
                .doOnNext(ticketNode -> this.syncResult(properties.getTenantId(),
                        resultSync.getRequestId(), ticketNode))
                .then();
    }

    @Override
    public Mono<Void> syncFast(ClientProperties properties) {
        ResultSync resultSync = ResultSync.withDefault("TIME-ENTRIES-SYNC");
        return this.filterCacheLastUpdateTime(properties)
                .contextWrite(ctx -> ctx.put("resultSync", resultSync))
                .doOnNext(companyNode -> this.syncResult(properties.getTenantId(),
                        resultSync.getRequestId(), companyNode))
                .doOnNext(resultNode -> this.recordAnchorTime(RedisKeys.TIME_ENTRIES_ANCHOR_REDIS_KEY_PREFIX
                        + properties.getTenantId(), resultNode.findValue("lastUpdated").textValue()))
                .then();
    }

    private Flux<JsonNode> fetch(ClientProperties properties, QueryParams queryParams) {
        return super.cwWebClient.fetch("/time/entries", queryParams)
                .contextWrite(ctx -> ctx.put("properties", properties));
    }

    private Flux<JsonNode> filterCacheLastUpdateTime(ClientProperties properties) {
        return this.readAnchorTime(RedisKeys.TIME_ENTRIES_ANCHOR_REDIS_KEY_PREFIX + properties.getTenantId())
                .map(sysTime -> "lastUpdated > [" + sysTime.format(DateTimeFormatter.ISO_DATE_TIME) + "]")
                .map(queryStr -> QueryParams.withDefault().setConditions(queryStr).setOrderBy("lastUpdated asc"))
                .flatMapMany(params -> this.fetch(properties, params))
                .contextWrite(ctx -> ctx.put("properties", properties));
    }

    private void syncResult(Long tenantId, UUID id, JsonNode resultNode) {
        this.sendEntity(RabbitKeys.TIME_ENTRIES_SYNC_QUEUE_KEY, ResultMsg.builder()
                .requestId(id).id(resultNode.get("id").longValue())
                .action(CallbackAction.none.name()).entity(resultNode).tenantId(tenantId)
                .syncDate(LocalDateTime.now()).build());
    }


}
